import sys
import os
from PySide6.QtWidgets import QApplication, QMainWindow, QPushButton, QVBoxLayout, QWidget, QMessageBox
from PySide6.QtMultimedia import QMediaPlayer
from PySide6.QtMultimediaWidgets import QVideoWidget
from PySide6.QtCore import QUrl
from PySide6.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply
import json


class VideoPlayer(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("甜妹视频播放器")
        self.resize(640, 480)

        # 创建视频播放组件
        self.video_widget = QVideoWidget()
        self.player = QMediaPlayer()
        self.player.setVideoOutput(self.video_widget)

        # 创建下载管理器
        self.network_manager = QNetworkAccessManager()
        self.network_manager.finished.connect(self.on_download_finished)

        # 创建按钮
        self.cache_button = QPushButton("缓存视频")
        self.cache_button.clicked.connect(self.cache_and_play)

        self.play_button = QPushButton("播放/暂停")
        self.play_button.clicked.connect(self.toggle_play)
        self.play_button.setEnabled(False)  # 初始状态禁用

        # 布局
        layout = QVBoxLayout()
        layout.addWidget(self.video_widget)
        layout.addWidget(self.cache_button)
        layout.addWidget(self.play_button)

        container = QWidget()
        container.setLayout(layout)
        self.setCentralWidget(container)

        self.video_path = None

    def cache_and_play(self):
        # 从接口获取视频地址
        api_url = "https://api.52vmy.cn/api/video/tianmei"
        self.network_manager.get(QNetworkRequest(QUrl(api_url)))

    def on_download_finished(self, reply: QNetworkReply):
        if reply.error() == QNetworkReply.NoError:
            data = reply.readAll().data()
            try:
                video_url = json.loads(data.decode())["data"]["video"]
                self.download_video(video_url)
            except Exception as e:
                pass
                # QMessageBox.critical(self, "错误", f"解析视频地址失败：{e}")
        else:
            QMessageBox.critical(self, "错误", f"请求失败：{reply.errorString()}")

    def download_video(self, video_url):
        self.video_path = "cached_video.mp4"
        if os.path.exists(self.video_path):
            os.remove(self.video_path)

        self.reply = self.network_manager.get(QNetworkRequest(QUrl(video_url)))
        self.reply.readyRead.connect(self.on_ready_read)
        self.reply.finished.connect(self.on_download_complete)

    def on_ready_read(self):
        with open(self.video_path, "ab") as f:
            f.write(self.reply.readAll())

    def on_download_complete(self):
        if self.reply.error() == QNetworkReply.NoError:
            self.play_button.setEnabled(True)
            QMessageBox.information(self, "提示", "视频缓存完成！")
        else:
            QMessageBox.critical(self, "错误", f"下载失败：{self.reply.errorString()}")

    def toggle_play(self):
        if self.video_path and os.path.exists(self.video_path):
            if self.player.mediaStatus() == QMediaPlayer.PlayingState:
                self.player.pause()
            else:
                self.player.setSource(QUrl.fromLocalFile(self.video_path))
                self.player.play()
        else:
            QMessageBox.warning(self, "提示", "请先缓存视频！")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    player = VideoPlayer()
    player.show()
    sys.exit(app.exec())